package cn.datawin.listener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.web.util.Log4jWebConfigurer;

import cn.datawin.bean.Constants;
import cn.datawin.bean.User;
import cn.datawin.util.JDBCUtil;
import cn.datawin.util.PropertiesUtil;
import cn.datawin.util.Resource;


public class DpmsListener implements ServletContextListener , HttpSessionListener{
	
	public static Set<HttpSession> sessions = new HashSet<HttpSession>();

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Log4jWebConfigurer.initLogging(sce.getServletContext());
		try {
			cn.datawin.util.DbUtil.connect();
			JDBCUtil.connect("/postgresql.properties");
			loadAppprops(sce.getServletContext().getRealPath("/"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		Log4jWebConfigurer.shutdownLogging(sce.getServletContext());
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessions.add(se.getSession()); 
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		sessions.remove(se.getSession());

	}
	
	public static List<User> getUser(){
		List<User> users = new ArrayList<User>();
		for(HttpSession session :sessions){
			User user = (User) session.getAttribute("user");
			if(user == null) continue;
			user.setCreationtime(session.getCreationTime());
			users.add(user);
		}
		return users;
	}
	
	public static void removeSession(String username){
		HttpSession _session = null;
		for(HttpSession session: sessions){
			User user = (User) session.getAttribute("user");
			if(user==null) continue;
			if(username.equals(user.getUsername())){
				_session = session;
				break;
			}
		}
		sessions.remove(_session);
		_session.invalidate();
	}
	
	void loadAppprops(String webRoot) throws IOException{
		Resource resource = new Resource("/WEB-INF/cfg/spider.properties");
		resource.setWebRoot(webRoot);
		Properties props = PropertiesUtil.loadProperties(resource);
		Constants.apps.putAll(PropertiesUtil.toMap(props));
		System.out.println("apps==="+ Constants.apps);
		
	}

}
